import { parseDeviceShareId } from '@/utils/deviceShare';
/* eslint-disable camelcase */
/**
 * 目前扫码有两个操作
 * 一个是绑定GPRS设备，一个是分享设备
 */
import { getItemForPk, isBLE, isGPRS } from '@/config/product';
import { getAppIDInfo, getTemplateConfig } from '@/config/template';
import deviceListModel from '@/models/deviceList';
import deviceShareModel from '@/models/deviceShare';
import gizwitsSdk from '@/models/gizwitsSdk';
import homesModel from '@/models/homes';
import { analysisQrcodeDevice } from '@/services/aepDeviceApi';
import { getProductConfigs } from '@/services/product';
import SDK from "@/utils/SDK";
import Taro from '@tarojs/taro';
import i18n from 'i18n-js';
import { checkIsLogin } from './loginStatus';
import Toast from './Toast';
import { bindAiDevice } from '@/services/ai';

const BASE_ICON = 'https://xbgroup-1251025085.cos.ap-guangzhou.myqcloud.com/cybertron/users/375869/media/GizwitsLogo_1655089046744.png';


const aepQRCodeKeyword = '?deviceId=';
const virtualDeviceKeyword = 'SSBT://';
const pkAndMacKeyword = 'PKMAC://';
const siteDeviceKeyword = '==';

interface ICybProductConfig {
  name: string;
  icon: string;
  app_id: string;
  product_config: string;
}


async function bindDevice(device: { mac: any; productKey: any; }, successFunc?: () => void, errorFunc?: () => void) {
  const data = await homesModel.addDevice({ device } as any);
  console.log('添加设备结果', data);
  if (data.success) {
    // 提示成功
    const BIND_SUCCEED = i18n.t('BIND_SUCCEED');
    Toast.success(BIND_SUCCEED);
    deviceListModel.getDeviceList();
    homesModel.initHomes();

    // 调用成功回调
    successFunc?.();
  } else {
    // 提示失败
    const { code } = data;
    if (code) {
      switch (parseInt(`${code}`, 10)) {
        case 2000046:
          Toast.error(i18n.t('DEVICE_NOT_SUPPORT_QRCODE_BIND'));
          break;
        case 2000045:
          Toast.error(i18n.t('THE_DEVICE_HAS_BEEN_BOUND_BY_OTHER_USERS'));
          break;
        case 2000063: {
          Toast.error(i18n.t('DEVICE_HAS_BIND_BUT_MULTIPLE'));
          break;
        }
        default:
          Toast.error(i18n.t('BIND_FAIL'));
          break;
      }
    }
    errorFunc?.();
  }
}


const bindDevcieByQRCode = async (
  res: any,
  successFunc: () => void,
  errorFunc: () => void
) => {
  Toast.loading(i18n.t('LOADING'));
  const result = await analysisQrcodeDevice({ content: res.result })
  if (result.success && result.data.mac && result.data.productKey) {

    const productKey = result.data.productKey
    const device = { mac: result.data.mac, productKey }
    // 检查是不是纯蓝牙设备，是的话，先帮设备注册到云端
    const config = getItemForPk(productKey)
    if (isBLE(config)) {
      const configRes = await SDK.deviceSafetyRegister(device);
      if (!configRes.success) {
        Toast.hideLoading();
        Toast.info(i18n.t('BLE_REGISTER_FAIL'));
        errorFunc();
        return;
      }
    }

    await bindDevice(device, successFunc, errorFunc).finally(() => {
      Toast.hideLoading();
    });
  } else {
    Toast.hideLoading();
    Toast.info(i18n.t('INVALID_QRCODE'));
    errorFunc();
  }
};

const bindWithPKAndMac = async (result: string) => {
  Taro.showLoading({
    title: '',
  })

  let rawData = result.replace(pkAndMacKeyword, '');
  const [pk, mac] = rawData.split(',');
  
  // 调用绑定接口
  const devices = [
    {
      product_key: pk,
      mac
    }
  ]
  const res = await bindAiDevice({ devices });
  console.log('resresresres', res)
  if (res.success && !res.data.data.failed) {
    deviceListModel.getDeviceList();
    Taro.showToast({
      title: "添加成功",
      icon: 'none',
    })
  } else {
    if (res.data.data.failed.length > 0) {
      const errorMsg = res.data.data.failed[0].msg
      switch (errorMsg) {
        case "device has been bound":
          Taro.showToast({
            title: "设备已被绑定",
            icon: 'error',
          })
          break;
        default:
          Taro.showToast({
            title: "绑定失败，请重试",
            icon: 'none',
          })
          break;
      }
      
    } else {
      Taro.showToast({
        title: "绑定失败，请重试",
        icon: 'none',
      })
    }
  }

  console.log('resresresres', res)
  Taro.hideLoading();
}

const virtualDeviceBind = async (
  res: any,
  successFunc: () => void,
  errorFunc: () => void
) => {

  Toast.loading(i18n.t('Loading'));
  /**
   * 解析
   */
  const str = res.result.replace(virtualDeviceKeyword, '');
  const attrs = str.split(',');
  const productConfig = await getProductConfigs({
    code: attrs[4],
  });
  console.log('configData', productConfig);

  if (productConfig.success) {
    /**
     * 更新配置文件 内部下载模版
     * 配置文件可能是多个，如果是多个分两种情况
     * 1.非superApp
     * 判断关联的appid是否是本app
     * 2.superApp
     * 提示让用户选择
     */
    if (productConfig.data.length === 0) {
      // 提示没有关联App
      Toast.error(i18n.t('NO_RELATIONSHIP_APP'));
      Toast.hideLoading();
      return;
    }

    const templateConfig = getTemplateConfig();
    if (templateConfig.isSuperApp) {
      // 大于1的数量，则提示
      let config = productConfig.data[0].product_config;
      if (productConfig.data.length > 1 && global.selectAppModal) {
        // 同步选择
        const contents = productConfig.data.map((item: ICybProductConfig) => {
          return {
            icon: item.icon || BASE_ICON,
            text: item.name || '-',
            productConfig: item.product_config,
          };
        });
        // 不隐藏会遮挡选择框
        Toast.hideLoading();
        const selectData: any = await global.selectAppModal.show(contents);
        config = selectData.productConfig;
      }
      Toast.loading(i18n.t('Loading'));
      await gizwitsSdk.addProduct(JSON.parse(config));
    } else {
      // 先判断appid
      let config = null;
      const localAppid = getAppIDInfo().appId;
      productConfig.data.forEach((item: ICybProductConfig) => {
        if (item.app_id === localAppid) {
          config = item.product_config;
        }
      });
      if (config) {
        await gizwitsSdk.addProduct(JSON.parse(config));
      } else {
        // 提示不存在
        Toast.hideLoading();
        Toast.error(i18n.t('PRODUCT_RELATIONSHIP_APP_ERROR'));
        return;
      }
    }
  } else {
    // 提示错误
    switch (productConfig.code) {
      case 400: {
        Toast.error(i18n.t('VIRTUAL_DEVICE_QRCODE_EXT'));
        break;
      }
      default: {
        Toast.error(i18n.t('FAILED_TO_PARSE_QRCODE'));
        break;
      }
    }
    Toast.hideLoading();
    return;
  }

  const device: any = { mac: attrs[2], productKey: attrs[0], did: attrs[1] };
  // `SSBT://${productKey},${did},${mac},${passcode}`
  const newDeviceData = await homesModel.addDevice({ device });

  // 刷新列表
  await homesModel.initHomes();
  await deviceListModel.getDeviceList();

  Toast.hideLoading();
  if (newDeviceData.success) {
    // 提示成功
    Toast.success(i18n.t('BIND_SUCCEED'));
    // 跳转过去

    // setTimeout(() => {
    //   console.log('goToDevicePage', device);
    //   homes.goToDevicePage(device, {});
    // }, 2000);

  } else {
    // 提示失败 确保是否用的是生成的app
    // 过滤错误码
    switch (newDeviceData.code) {
      case 2000045: {
        Toast.error(i18n.t('THE_DEVICE_HAS_BEEN_BOUND_BY_OTHER_USERS'));
        break;
      }
      case 2000063: {
        Toast.error(i18n.t('DEVICE_HAS_BIND_BUT_MULTIPLE'));
        break;
      }
      default: {
        Toast.error(i18n.t('CONFIRM_USE_GENERATED_APP'));
      }
    }
  }
  return;
}

const handleShare = async (result) => {
  const shareId = await parseDeviceShareId(result);
  if (shareId) {
    deviceShareModel.acceptShare(shareId);
  } else {
    Toast.info(i18n.t('INVALID_QRCODE'));
  }
}


export default () => {
  if (checkIsLogin()) {
    Taro.scanCode({
      scanType: ['qrCode'],
      fail: (e) => {
        console.log('e', e);
      },
      success: ({ result }) => {
        console.log('result', result)
        if (result.includes(siteDeviceKeyword)) {
          bindDevcieByQRCode({ result }, () => { }, () => { });
        } else if (result.includes(aepQRCodeKeyword)) {
          const start = result.indexOf(aepQRCodeKeyword);
          const params = `sno#${result.substring(
            start + aepQRCodeKeyword.length,
            result.length
          )}`;
          bindDevcieByQRCode({ result: params }, () => { }, () => { });
        } else if (result.includes(virtualDeviceKeyword)) {
          virtualDeviceBind({ result }, () => { }, () => { })
        } else if (result.includes(pkAndMacKeyword)) {
          bindWithPKAndMac(result);
        }  else {
          const [pk, ...rest] = result.split(':');
          const mac = rest.join(':');
          const product = pk && mac && getItemForPk(pk);
          if (product && isGPRS(product)) {
            Toast.loading(i18n.t('LOADING'));
            bindDevice({ mac, productKey: pk }).finally(() => {
              Toast.hideLoading();
            });
          } else {
            handleShare(result)
          }
        }
      }
    })
  }
}
